Skip to content

Per-bin work of integer planes in NumPy int64 (speed plan D6), bitwise v0.7.0 - #104

Merged
guijacquemet merged 4 commits into
mainfrom
perf/numpy-per-bin
Nov 16, 2026
Merged

guijacquemet merged 4 commits into
mainfrom
perf/numpy-per-bin

Conversation

@guijacquemet

@guijacquemet guijacquemet commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Step D6 of the preprocessing speed plan. Owner decision (16 Nov): no Numba; do the exact NumPy change here. Evidence: preprocessing draft PR #318, experiments/histogram_numba_study/ (its numba_patch.py numpy-bins mode is the sketch this follows).

Do not merge yet: an independent review comes first. No tag.

What changes (commit 1, f78cd0b)

Until now, every integer plane ran Python loops over every bin, on preprocessing's calling thread:

  • _integer_bin_starts built a 65,537-item list per call. It ran once for the counts, again for the cached bin limits, and 4× for the range check's _bin_index + bisect.
  • The bin limits, representatives and max_representative_error were list comprehensions over the bins.
  • _counts_from_per_value built the bin index of every value from that list.

New pure module integer_bins (moved out of histogram.py, which shrinks; layer and AGENTS map added). It keeps the same formulas:

Piece Now Python integers of v0.7.0 kept when (explicit, tested condition)
bin starts ceil(i*W/n) / min(i, W) int64 arange arithmetic (NumPy floor division = Python's) bin_count * width >= 2**62 (64-bit planes with a wide range), so i*width can never overflow
per-value counts → bins int64 cumulative sums at the starts float64 total >= 2**52: v0.7.0's float64 bincount + rint is kept, so even its rounding beyond 2**53 is unchanged (unreachable for one plane in memory)
bin limits (_integer_bin_limits) int64 arrays the above, or limits that are not Python ints (a caller's NumPy integers): v0.7.0's lists, so its result types (np.int64, np.float64) stay too
representatives ((first+lo)+(last+lo)).astype(float64)/2: exact below 2**53 pixels from 2**51 (beyond_float_exact), or no int64 limits; the Fraction bound (#28) is unchanged
max_representative_error int((last-first).max()) + 1 no int64 limits
bin of an order statistic (range check) O(1) exact integer division: offset*n // width, or offset if width <= n none needed: Python ints throughout

Unchanged: float binning and bin positions, tail moments (exact rationals), 32/64-bit pixel binning, and the radix selection. There is no new dependency, and no API, file-format or message change. CHANGELOG ## Unreleased is updated.

Identity

Permanent differential test (commit 2, 74d72a0). tests/histogram_parity_cases.py ports the study's diffcheck.py, made smaller: 4,236 cases.

  • Cases:
    • all 10 dtypes;
    • NaN and ±inf; subnormals; constant, all-NaN, empty and dtype-extreme planes;
    • bin-edge float grids (with nextafter neighbours);
    • bin counts default, 1, 3, 256, 500 and 10,000 (plus 4,096 and 65,536 on 64-bit ranges);
    • min-max and robust ranges; whole planes and 3 blocks;
    • 64-bit ranges on both sides of each int64 condition: n*W just below and at 2**62, below 2**51 but too wide for int64 at 65,536 bins, at 2**51, and the full uint64 top half.
  • Fields: every PlaneHistogram field (arrays and floats as raw bytes), representatives, max_representative_error, integer_bin_limits() values and types, is_exact, and the RangeCheck, from both compute_block_histogram and histogram_with_range_check.
  • Reference: tests/data/histogram_v070_parity.json is the table recorded on v0.7.0 (c6a9f9d) (one SHA-256 per plane, 23 KB).
  • tests/test_histogram_parity.py checks:
    • every plane against that table;
    • the same planes with the int64 paths switched off (INT64_STARTS_LIMIT = 0): the kept Python path gives the same bits;
    • a negative control: one bin off, or a representative one ulp off, changes the digest;
    • each int64 formula against the Python integers, including an exhaustive bisect check of the bin index;
    • each guard at its boundary (2**62, 2**52 totals with [2**53, 1], NumPy-integer limits).
  • Result: 0 of 4,236 differ.
  • Signed zeros, a pre-existing cross-platform difference. The table's planes never mix -0.0 and +0.0 (+ 0.0 is added to every float plane), and an all--0.0 plane covers negative zero.
    • In the first CI run, the Windows and macOS runners gave other pixel_min/pixel_max bits than Linux for the six planes that mixed them, while Linux passed.
    • These are float planes, and this change does not touch their path (finite.min()/max()). The cause is inferred: NumPy may return either zero depending on the platform. v0.7.0 itself was not run on those runners.
    • It is not fixed here; it is listed as a follow-up below. It can make plane_histograms.csv say -0.0 on one OS and 0.0 on another for the same pixels.

Further identity checks on this machine:

  • Study's full diffcheck.py case set, run in separate processes on v0.7.0 and on this branch and compared field by field: 0 of 5,580 cases differ.
  • tools/dump_outputs.py, base vs. change: default 032b395b… (1,788 lines) and --corpus 0111f8bd… (4,764 lines), the same on both.
  • Normalization suite:
    • tools/check.py: 2,629 passed, 90 skipped. The skips are the scikit-image extra, the same as on base, which CI's histology job runs.
    • Goldens (test_fit_goldens.py, the stain and region parity tables) pass.

Preprocessing v0.6.1 (37c583e) with this branch installed --no-deps:

  • tests/test_run_workers_bytes.py (Spec fixtures v05, v09, workers 1/2/4/auto) and tests/test_histogram_goldens.py (12): 15 passed.
  • Cross-version raw bytes. Each worker run's files were hashed under v0.7.0 and under this branch, with a fixed --basetemp and the inputs' mtimes pinned, since the manifest records them and the test writes new inputs each session. Result: 10 runs, 60 files, 0 differ (CSV, design, manifest, reports).
  • Full preprocessing suite (dev, zarr and notebook extras): 6,020 passed, 4 skipped (the same platform skips as in the study), 1 failed.
    • The failure is test_notebook_design_confirm_speed.py::test_the_click_saves_once…, a wall-clock assertion on a machine with load average about 3.
    • It does not touch normalization. Rerun alone, it passed 3/3 under each version.
  • Benchmark data: all 40 runs below wrote identical bytes in all 6 files (fixed clock, one output folder).

Speed (commit 3, a70b0df)

Setup:

  • The study's data: benchmark_run_workers.write_dataset at scale 1, 14 images, 76 planes, 303 MiB, memory limit 64 MiB.
  • Its runonce.py: a fresh process per run, fixed clock.
  • An interleaved driver modelled on bench.py, with v0.7.0 and this change selected by PYTHONPATH (the module path was checked for each variant).
  • 5 repeats in rotating order.
  • Machine: Linux, 4 shared CPUs, load 2.6–3.4, Python 3.13.18, NumPy 2.5.5.

Wall time of run_experiment, median (min–max):

workers v0.7.0 this change speed-up vs v0.7.0 serial median CPU s
1 (serial) 7.23 (6.25–7.70) 4.95 (4.66–5.31) 1.46× 1.46× 6.6 → 4.9
2 6.24 (5.78–6.63) 4.16 (4.10–5.04) 1.50× 1.74× 6.8 → 5.3
4 6.18 (5.66–6.52) 4.78 (4.16–5.17) 1.29× 1.51× 7.3 → 5.4
auto (4) 6.40 (5.54–6.56) 4.51 (4.11–4.75) 1.42× 1.61× 7.1 → 5.5

This matches the study's numpy-bins (1.48× serial, 1.31× at 4 workers). At every worker count, the slowest run of this change is faster than the fastest run of v0.7.0 (the min–max ranges do not overlap).

The normalization suite also gets faster: 51 s → 20 s on the old tests; 45 s with the new parity tests.

Release (not done here)

This needs normalization v0.7.1 (patch: version bump + CHANGELOG heading, tag by the owner), then re-pins of the bricks that pin @v0.7.0:

  • morphobricks-preprocessing:
    • pyproject.toml.
    • Its notebook install cell, if it pins.
    • versions.py writes morphobricks_normalization.__version__ into run_manifest.json, so manifests will say 0.7.1 by design. Check test_manifest.py, test_notebook_setup.py and the histogram goldens for a hard-coded 0.7.0.
    • Then its own patch release.
  • CellPatcher: setup.py (+ tests/test_dependency_pins.py).
  • fiberfeatures: pyproject.toml (+ tests/test_dependency_pins.py). Its normalization requirement must equal the one in the preprocessing release it pins, so re-pin it after preprocessing.

Follow-up outside D6 (not a speed item)

  • Signed-zero extrema. _wide_histogram takes pixel_min/pixel_max of float planes from NumPy's min/max. For a plane holding both -0.0 and +0.0, the sign of the result differs between platforms (Linux vs. the Windows and macOS runners), so its text and bits in plane_histograms.csv can differ.
    • Deciding a rule (for example, -0.0 whenever present) is a behaviour change for the owner.

Not done here: candidates for step D8 (own PRs)

  • csv_io.table_header rebuilds the 131,110 column names for every staged file. It could be cached per (channel IDs, bin count).
  • csv_io._row formats the counts with map(str, counts.tolist()); csv.writer cell writing is >50% of GIL time after this change. A faster exact formatter needs its own byte-identity study.
  • csv_io._histogram parses counts from text with np.array(list_of_str, int64).
  • summaries._saturated_fraction builds the whole integer_bin_limits() list to read one bin. It could read the cached int64 limits.
  • integer_bin_limits() still returns a list of tuples by design (public API). Internal callers could use the arrays instead.
  • wide_integer_error (64-bit beyond 2**51) loops in Fraction over every bin. This is exact by design; vectorising it is not easy and is rarely hit.

🤖 Generated with Claude Code

https://claude.ai/code/session_01G3qp9AxjpGPw9xfWAUJNqc

The bin starts, the sums of per-value counts into bins, the integer bin
limits, the representatives, max_representative_error and the bin of each
order statistic of the range check were Python loops over every bin (a
65,537-item list per plane and call). New module integer_bins computes the
same integers with NumPy int64, and keeps v0.7.0's exact Python integers
where int64 could not be exact: bin_count * width >= 2**62, pixels from
2**51 on, per-value totals from 2**52 on, and histograms built with NumPy
integer limits. Every output is bitwise v0.7.0's; no new dependency.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01G3qp9AxjpGPw9xfWAUJNqc
tests/histogram_parity_cases.py ports the preprocessing study's differential
check (PR #318, diffcheck.py), made smaller: 4,236 cases over the ten pixel
types, NaN/inf, subnormals, constant/empty/extreme planes, bin-edge float
grids, several bin counts, min-max and robust, whole and in 3 blocks, and
64-bit ranges on both sides of every int64 condition.
tests/data/histogram_v070_parity.json is its table recorded on v0.7.0
(c6a9f9d). test_histogram_parity.py checks every plane against it, the kept
Python path with the int64 path switched off, a negative control, and each
int64 formula and condition against the Python integers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01G3qp9AxjpGPw9xfWAUJNqc
The preprocessing study's data and scripts (PR #318), preprocessing v0.6.1,
5 interleaved repeats of v0.7.0 and this change at workers 1/2/4/auto on a
shared 4-CPU machine; median (min-max) wall times in the CHANGELOG. All 40
runs wrote identical bytes in every output file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01G3qp9AxjpGPw9xfWAUJNqc
A caller-built PlaneHistogram may carry a NumPy integer bin count. Then
bin_count * width in integer_bin_starts_int64 is a NumPy product that
wraps silently: a uint64 histogram over 0 .. 2**50 with
np.int64(65_536) bins got negative bin limits and representatives,
where v0.7.0 raised OverflowError; narrower ranges returned Python ints
where v0.7.0 gave np.int64 limits and an np.float64 bound.
integer_bin_offsets now takes the int64 path only when the bin count is
a Python int as well, so these histograms keep v0.7.0's values, types
and refusals. Computed histograms are unaffected (validate_bin_count
returns int).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01G3qp9AxjpGPw9xfWAUJNqc

@guijacquemet guijacquemet left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent review: PASS after one fix (5373049)

Defect found and fixed: a NumPy bin count on a caller-built histogram

integer_bin_offsets checked that the limits were Python ints, but not the bin count. PlaneHistogram does not convert bin_count, so a caller can pass np.int64(65_536). Then bin_count * max(width, 1) in integer_bin_starts_int64 is a NumPy product that wraps silently, and the 2**62 guard passes.

  • Example: a uint64 histogram over 0 .. 2**50 with np.int64(65_536) bins. On a70b0df it got negative bin limits (last bin (-17179869183, 0)) and negative representatives, with no error. v0.7.0 raised OverflowError here.
  • Narrower ranges: with a NumPy bin count it returned Python int limits and a float bound, where v0.7.0 gave np.int64 limits and np.float64.

Fix: the int64 path now also needs type(bin_count) is int, so these histograms keep v0.7.0's values, types and refusals. Computed histograms are not affected, because validate_bin_count returns int.

  • Regression test: test_bin_offsets_keep_python_integers_for_a_numpy_bin_count. It fails on a70b0df and passes with the fix.
  • The CHANGELOG line is updated.

Exactness of each int64 path (checked against the v0.7.0 formulas)

  • Starts: with n*W < 2**62, |i*W| < 2**62 and NumPy's floor division is Python's, so the starts are the same integers. The width <= n branch is the same.
  • Per-value sums: the guard is the float64 total < 2**52. Below 2**53, every partial sum of non-negative counts is exact in float64, so the guard itself is exact, and v0.7.0's bincount + rint equals the int64 cumsum differences. The threshold could be 2**53; 2**52 is conservative.
  • Representatives: the invariant pixel_min <= binning_min <= binning_max <= pixel_max and beyond_float_exact keep |first+lo + last+lo| < 2**52. So the int64 sum is exact in float64 and /2 is exact, which is the same as Python's correctly rounded int / 2.
  • max_representative_error: the widest bin is the same integer.
  • integer_bin_index: the count of i < n with ceil(i*W/n) <= o is min(floor(o*n/W), n-1) + 1. It uses Python ints only (_key_value gives .item(), and the limits are Python ints), so floor semantics and negatives match: o < 0 gives -1, as bisect does.
  • Types at public boundaries: integer_bin_limits() uses .tolist(), so it returns Python ints; the bound is a float and RangeCheck fields are ints. These match v0.7.0.

Parity table

  • I re-recorded the whole table on a c6a9f9d worktree. It is byte-identical to tests/data/histogram_v070_parity.json.
  • Parity tests: 396 passed on a70b0df, 397 with the fix.
  • Branch coverage of the table-only test over integer_bins: every int64/Python choice that real computations can reach is hit on both sides.
    • The table never reaches the offset < 0 and width <= n branches of integer_bin_index: no non-exact histogram has a range check with width <= n. The exhaustive bisect unit test covers them.
    • The float64 fallback of counts_from_per_value cannot be reached from a plane in memory; a unit test covers it.
  • The negative control works: one bin off, or one ulp off, changes the digest.

Identity, reproduced

Check Result
tools/check.py (fix head) 2,630 passed, 90 skipped (scikit-image extra; the CI histology job ran them), rules OK
Preprocessing v0.6.1 37c583e, this branch --no-deps: test_run_workers_bytes.py (v05, v09) 4 passed
Full preprocessing v0.6.1 suite (zarr, notebook and dev extras) 6,021 passed, 4 skipped (platform skips: case-sensitive file system, root ignoring file modes)
Benchmark data (scale 1, fixed clock): v0.7.0 vs branch, workers 1 and 4, 16 runs in all all 6 files' SHA-256 identical to v0.7.0 serial

Signed zero

Confirmed pre-existing on v0.7.0. compute_plane_histogram gives pixel_min = -0.0 for [0.0, -0.0, 1.0] and +0.0 for [-0.0, 0.0, 1.0]: it follows ndarray.min, which depends on element order and layout.

  • The float path is untouched by this diff.
  • + 0.0 is applied only in _float_plane. It does not consume the random generator, and integer planes are generated separately, so it hides nothing about the int path.
  • Not fixed here. I agree it is an owner decision.

Speed (shared 4-CPU machine, load about 1.0–1.3, fresh process per run, 3 repeats, interleaved)

workers v0.7.0 branch speed-up
1 6.48 s (6.28–6.54) 4.91 s (4.88–4.94) 1.32×
4 5.47 s (5.47–5.97) 4.06 s (3.84–4.43) 1.35×

Median CPU time: 6.6 → 5.0 s serial and 7.1 → 5.8 s at 4 workers. The ranges do not overlap. The serial gain is smaller than the stated 1.46×, mostly because v0.7.0 ran faster here on a less loaded machine; it is the same order.

CI is 10/10 green on 5373049. Merging.


Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants